﻿using System;
using System.IO;
using System.Windows;
using HostEdit.Properties;

namespace HostEdit
{
    public static class ExecuteClass
    {


        public const string RootfileTemplate = @"{0}\System32\drivers\etc\hosts";

        public static String entete;

        public static void WriteHost(Hosts ContextHosts)
        {

            string root = Environment.GetFolderPath(Environment.SpecialFolder.Windows, Environment.SpecialFolderOption.None);
            string rep = string.Format(RootfileTemplate, root);

            try
            {

                FileInfo f = new FileInfo(rep);
                if (f.Attributes != FileAttributes.Normal)
                {
                    f.Attributes = FileAttributes.Normal;
                }              

            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format(Resources.AccessFileErrorTo01TryToRestartTheApplicationWithAdministrator, rep, ex.Message), Resources.AccessFileError, MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }


            System.IO.StreamWriter j = null;

            try
            {
                j = new System.IO.StreamWriter(rep);
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format(Resources.AccessFileErrorTo01TryToRestartTheApplicationWithAdministrator, rep, ex.Message), Resources.AccessFileError, MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            

            j.WriteLine(entete);
            j.WriteLine(String.Empty);

            foreach (Host Host in ContextHosts)
            {
                j.WriteLine(String.Empty);

                foreach (Adress Adr in Host.Address)
                    if (Adr.Active)
                        j.WriteLine(String.Format("\t\t{0}\t\t{1}", Adr.Value, Host.Name));
                    else
                        j.WriteLine(String.Format("#\t\t{0}\t\t{1}", Adr.Value, Host.Name));
            }
            j.Close();

        }

    }
}
